#!/usr/bin/perl

use POE qw(Component::Rendezvous);

use Data::Dumper;

POE::Session->create(
    inline_states => {
        _start => \&_start,
        discovered => \&discovered,
        entries => \&entries,
        test => \&test,
    },
);

sub _start {
    $_[HEAP]->{server} = POE::Component::Rendezvous->new(
        debug => 1,
        alt_fork => (($ARGV[0]) ? $ARGV[0] : 0),
        rendezvous_options => [
            "daap" 
        ], # could put something here, or omit it
    );
    warn "started\n";
    $_[KERNEL]->yield('test');
    #$self->connect({ event => 'connected' });
    # alternative way
    $_[HEAP]->{server}->yield(discover => { event => 'discovered' });
}

sub discovered {
    warn "discovered: $_[ARG0]->{result}\n";
    $_[HEAP]->{server}->entries({ event => 'entries', extra_data => sub { 'testing!' }, wantarray => 1 });
    warn "getting entries\n";
}

sub entries {
#    warn "entries: ".Data::Dumper->Dump([$_[ARG0]->{result}])."\n";
    foreach my $entry ( @{$_[ARG0]->{result}} ) {
        printf "%s %s:%s\n", $entry->name, $entry->address, $entry->port;
    }
    $_[HEAP]->{server}->shutdown;
    $_[KERNEL]->alarm_remove_all();
}

sub test {
    warn ".\n";
    $_[KERNEL]->delay_set('test' => 1);
}

$poe_kernel->run();

exit;
